package com.ytg.myapi;

import android.app.Activity;
import android.view.View;

import com.ytg.myapi.finder.ActivityFinder;
import com.ytg.myapi.finder.Finder;
import com.ytg.myapi.finder.ViewFinder;
import com.ytg.myapi.utils.SetCheckedBack;
import com.ytg.myapi.utils.SetTextBack;

import java.util.HashMap;
import java.util.Map;

public class BindWay {
    private static volatile BindWay sInstance;
    public BindWay() {
    }

    private static final ActivityFinder ACTIVITY_FINDER = new ActivityFinder();

    private static final ViewFinder VIEW_FINDER = new ViewFinder();

    private static Map<String, Injector> FINDER_MAP = new HashMap<>();
   public  SetTextBack textBack;
   public SetCheckedBack checkedBack;
    public static BindWay getInstance() {
        if (sInstance == null) {
            synchronized (BindWay.class) {
                if (sInstance == null) {
                    sInstance = new BindWay();
                }
            }
        }
        return sInstance;
    }
    public void setTextBack(SetTextBack back){
        this.textBack = back;
    }

    public void setCheckedBack(SetCheckedBack checkedBack) {
        this.checkedBack = checkedBack;
    }

    public static Injector bind(Activity activity) {
       return bind(activity, activity, ACTIVITY_FINDER);
    }

    public static void bind(View view) {
        bind(view, view);
    }

    public static void bind(Object host, View view) {
        bind(host, view, VIEW_FINDER);
    }

    /**
     * 获取目标类
     *
     * @param host
     * @param source
     * @param finder
     */
    public static Injector bind(Object host, Object source, Finder finder) {
        String className = host.getClass().getName();
        try {
            Injector injector = FINDER_MAP.get(className);
            if (injector == null) {
                Class<?> finderClass = Class.forName(className + "$$Injector");
                injector = (Injector) finderClass.newInstance();
                FINDER_MAP.put(className, injector);
            }
           return  injector.inject(host, source, finder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public Injector getInjector(Activity activity){
        String className = activity.getClass().getName();
        try {
            Injector injector = FINDER_MAP.get(className);
            if (injector == null) {
                Class<?> finderClass = Class.forName(className + "$$Injector");
                injector = (Injector) finderClass.newInstance();
                FINDER_MAP.put(className, injector);
            }
            return injector;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
